<script setup>
import {ref} from 'vue';
// 引入添加渠道的api
import {updateSourceApi, getSourceTreeApi} from '@/service/source.js';
import {ElMessage} from "element-plus";

const emit = defineEmits(['reload']);
const reload = () => {
  emit('reload');
}

const dialogVisible = ref(false);

// 加载渠道树
const treeData = ref([]);
const fetchTreeData = () => {
  getSourceTreeApi().then(res => {
    treeData.value = res.data.tree;
  });
};

const form = ref({
  id: '',
  parent_id: '',
  title: ''
});
// 设置form的验证规则
const rules = ref({
  title: [
    {required: true, message: '请输入渠道名称', trigger: "blur"}
  ]
});

// 初始化form
const initForm = () => {
  form.value = {
    id: '',
    parent_id: '',
    title: ''
  };
};

const openDialog = (row) => {
  fetchTreeData();
  form.value = row;
  dialogVisible.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  initForm();
};

// 提交表单
const formRef = ref(null);
const handleSave = () => {
  // 表单验证后提交
  formRef.value.validate(async (valid) => {
    console.log(valid)
    if (valid) {
      try {
        const response = await updateSourceApi(form.value);
        if (response.code === 200) {
          ElMessage.success(response.msg);
          closeDialog();
          reload();
        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        ElMessage.error('添加渠道失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

defineExpose({
  openDialog
});

</script>

<template>
  <el-dialog v-model="dialogVisible" title="创建渠道" width="300">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-form-item label="父级渠道" prop="parent_id">
        <el-cascader v-model="form.parent_id" :options="treeData"
                     :props="{label:'title', value:'id' ,checkStrictly: true, emitPath: false }" placeholder="请选择父级渠道"
                     style="width:100%"></el-cascader>
      </el-form-item>
      <el-form-item label="渠道名称" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>